package com.zhangmeng.online.exam.ui.controller;

import com.alibaba.fastjson2.JSONObject;
import com.zhangmeng.online.exam.ui.admin.PaperPage;
import com.zhangmeng.online.exam.ui.utils.ApiUtils;
import com.zhangmeng.online.exam.ui.module.User;
import com.zhangmeng.online.exam.ui.service.UserService;
import com.zhangmeng.online.exam.ui.utils.AlertUtils;
import com.zhangmeng.online.exam.ui.utils.FxUtils;
import com.zhangmeng.online.exam.ui.utils.HttpUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zm
 * @date 2025/3/31 14:33
 * @version: 1.0
 */
public class LoginController {

    @FXML
    public TextField username;

    @FXML
    public TextField password;

    //验证码
    @FXML
    public ImageView captcha_image;

    @FXML
    public TextField verificationCode;

    @FXML
    public Button loginButton;

    @FXML
    public void initialize() {
        captcha_image.setImage(new Image(ApiUtils.API_URL + "/verificationCode/generate"));
        captcha_image.setFitHeight(30);
        captcha_image.setFitWidth(140);

        captcha_image.setOnMouseClicked(event -> {
            captcha_image.setImage(new Image(ApiUtils.API_URL + "/verificationCode/generate"));
        });

        username.setText("admin");
        password.setText("123456");

        loginButton.setOnAction(event -> {
            login();
        });

    }

    private void login() {

        //TODO 登录逻辑
        Map<String, Object> params = new HashMap<>();
        params.put("username", username.getText());
        params.put("password", password.getText());
        params.put("captcha", verificationCode.getText());
        String response = HttpUtils.POST(ApiUtils.API_URL + "/login", params);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("code") == 2001) {
            Map<String, Object> data = (Map<String, Object>) jsonObject.get("data");
            Object token = data.get("token");
            System.out.println("token:" + token);
            HttpUtils.USER_INFO.put("token", token);

            User user = new User();
            user.setUsername(username.getText());
            user.setPassword(password.getText());
            user.setToken(token.toString());
            UserService.setCurrentUser(user);

            admin_page();

//            new Thread(UserService::user_type).start();
//            Alert alert = AlertUtils.alert_msg(jsonObject.getString("message"));

//            LoginController.MyScheduledService myService = new LoginController.MyScheduledService();
//            //myService.setDelay(Duration.seconds(5));//延迟
//            myService.setPeriod(Duration.millis(500));//时间周期
//            myService.setRestartOnFailure(true);
//            myService.setMaximumFailureCount(4);//设置最大失败次数
//
//            myService.progressProperty().addListener(new ChangeListener<Number>() {
//                @Override
//                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
//                    System.out.println("progressProperty:" + newValue.intValue());
//                }
//            });
//
//            myService.valueProperty().addListener(new ChangeListener<Number>() {
//                @Override
//                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
//                    if (newValue != null) {
//                        System.out.println("progressProperty:" + newValue.intValue());
//                    }
//                }
//            });
//
//            myService.lastValueProperty().addListener(new ChangeListener<Number>() {
//                @Override
//                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
//
//                    if (newValue != null) {
//                        System.out.println("lastValueProperty:" + newValue.intValue());
//                        if (newValue.intValue() == 3) {
//                            myService.cancel();
//                            //alert.close();
//                            //success();
//                            admin_page();
//                        }
//                    }
//                }
//            });
//
//            myService.start();


        } else {
            AlertUtils.alert_warning(jsonObject.getString("message"));
        }
    }



    private void success() {
        String type = UserService.getCurrentUser().getRoleType();
        switch (type) {
            case "STUDENT" -> user_page();
            case "ADMIN" -> admin_page();
        }
    }

    private void user_page() {
        Scene scene = loginButton.getScene();
        Stage window = (Stage) scene.getWindow();
        window.close();

        Stage stage = new Stage();

        //判断
        PaperPage paperPage = new PaperPage(new HashMap<>());
        scene = new Scene(paperPage, 1280, 720);
        stage.setScene(scene);
        stage.setTitle("在线考试系统");
        stage.show();
    }

    private void admin_page() {
        Scene scene = loginButton.getScene();
        Stage window = (Stage) scene.getWindow();
//        IndexPage indexPage = new IndexPage();
        try {
            Parent main = FXMLLoader.load(this.getClass().getResource("/fxml/main.fxml"));
            scene = new Scene(main, FxUtils.DEFAULT_WIDTH, FxUtils.DEFAULT_HEIGHT);
            window.setScene(scene);
            window.setResizable(true);
            window.centerOnScreen();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    class MyScheduledService extends ScheduledService<Number> {

        int sum = 0;

        @Override
        protected Task<Number> createTask() {

            return new Task<Number>() {
                @Override
                protected Number call() throws Exception {
                    sum = sum + 1;

                    return sum;
                }

                @Override
                protected void updateValue(Number value) {

                    super.updateValue(value);
//                    System.out.println("updateValue");
                    if (value.intValue() == 10) {
                        LoginController.MyScheduledService.this.cancel();
                    }

                }
            };
        }
    }
}
